<script>
import CustomButton from "@/components/button/index.vue";
import CustomTitle from "@/components/title/index.vue";
import { ref, watch } from "vue";
import { marked } from "marked";
import { generateStudyPlan } from "@/api/api.js";
import { TokenService } from "@/stores/userStore.js";
import { List, Delete } from "@element-plus/icons-vue";

export default {
  name: "StudyPlan",
  components: {
    CustomButton,
    CustomTitle,
    List,
    Delete,
  },
  setup() {
    const durationOptions = ["20", "40", "60", "80"];
    const selectedDuration = ref("");
    const subject = ref(""); // 绑定学习科目
    const goal = ref(""); // 绑定学习目标
    const duration = ref(""); // 绑定计划时长

    // 默认 Markdown 模板
    const markdownTemplate = `# Vue.js 学习笔记

        ## 1. 概述
        记录 Vue.js 的核心概念和学习过程中的重点内容。

        ## 2. 目标
        - 掌握 Vue.js 基础语法
        - 理解组件化开发
        - 熟悉 Vuex 状态管理

        ## 3. 核心内容

        ### 3.1 Vue 实例
        - **创建实例**：
          \`\`\`javascript
          const app = new Vue({
            el: '#app',
            data: {
              message: 'Hello Vue!'
            }
          });
          \`\`\`
        `;

    const markdownInput = ref(markdownTemplate); // 绑定用户输入的 Markdown 内容
    const parsedMarkdown = ref(marked(markdownTemplate)); // 存储解析后的 HTML

    // 监听 markdownInput 的变化，实时解析 Markdown
    watch(markdownInput, (newValue) => {
      parsedMarkdown.value = marked(newValue);
    });

    const generatePlan = () => {
      // 生成规划的逻辑
      const user_id = TokenService.getCurrentUserId();
      generateStudyPlan(
        user_id,
        subject.value,
        goal.value,
        duration.value
      ).then((res) => {
        if (!res.success) {
          alert(res.message);
        } else {
          alert(res.message);
          markdownInput.value = res.plan;
          parsedMarkdown.value = marked(markdownInput.value);
        }
      });
    };
    const exportPlan = () => {
      if (!markdownInput.value) {
        alert("请先生成规划");
      } else {
        const blob = new Blob([markdownInput.value], { type: "text/plain" });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = "study_plan.md";
        link.click();
        URL.revokeObjectURL(url);
      }
    };

    const showListModal = ref(false);
    const tasks = ref([
      { id: 1, content: "学习Python定量和数据类型基础", completed: true },
      { id: 2, content: "学习基本运算和表达式", completed: false },
      { id: 3, content: "学习条件判断if-else语句", completed: false },
      { id: 4, content: "学习for和while循环", completed: false },
      { id: 5, content: "学习Python函数的定义和使用", completed: false },
      { id: 6, content: "开发一个简单的Python小程序", completed: false },
      { id: 7, content: "学习并使用Python常用库", completed: false },
    ]);

    const showStudyList = (event) => {
      event.preventDefault();
      event.stopPropagation();
      showListModal.value = true;
    };

    const closeModal = (event) => {
      if (event) {
        event.preventDefault();
        event.stopPropagation();
      }
      showListModal.value = false;
    };

    const toggleTask = (taskId) => {
      const task = tasks.value.find((t) => t.id === taskId);
      if (task) {
        task.completed = !task.completed;
      }
    };

    return {
      durationOptions,
      selectedDuration,
      subject,
      goal,
      exportPlan,
      duration,
      markdownInput,
      parsedMarkdown,
      generatePlan,
      showStudyList,
      showListModal,
      tasks,
      closeModal,
      toggleTask,
    };
  },
};
</script>

<template>
  <div class="study-plan">
    <div class="header">
      <CustomTitle
        :title="$t('study-plan.exportPlan')"
        icon="Edit"
      ></CustomTitle>
      <CustomButton
        :label="$t('study-plan.exportPlan')"
        @click="exportPlan"
      ></CustomButton>
    </div>
    <div class="body">
      <div class="left">
        <form class="study-form">
          <div class="form-group">
            <label for="subject"
              >{{ $t("study-plan.subjectPlaceholder") }}：</label
            >
            <input
              type="text"
              id="subject"
              v-model="subject"
              :placeholder="$t('study-plan.subjectPlaceholder')"
            />
          </div>
          <div class="form-group">
            <label for="goal">{{ $t("study-plan.goalPlaceholder") }}：</label>
            <textarea
              id="goal"
              v-model="goal"
              :placeholder="$t('study-plan.goalPlaceholder')"
            ></textarea>
          </div>
          <div class="form-group">
            <label for="duration"
              >{{ $t("study-plan.durationPlaceholder") }}：</label
            >
            <el-select
              id="duration"
              v-model="duration"
              :placeholder="$t('study-plan.durationPlaceholder')"
            >
              <el-option
                v-for="option in durationOptions"
                :key="option"
                :value="option"
                :label="option"
                style="padding-left: 20px; font-size: 15px"
              />
            </el-select>
          </div>
          <div class="button-group">
            <CustomButton
              :label="$t('study-plan.generatePlan')"
              @click="generatePlan"
              style="width: 150px"
            ></CustomButton>
            <button class="study-list-button" @click="showStudyList">
              <el-icon><List /></el-icon>
              学习清单
            </button>
          </div>
        </form>
      </div>
      <div class="middle">
        <!-- Markdown 输入框 -->
        <el-input
          v-model="markdownInput"
          type="textarea"
          :rows="15"
          placeholder="在这里输入 Markdown 笔记..."
          class="markdown-input"
          spellcheck="false"
        />
      </div>
      <div class="right">
        <!-- Markdown 预览 -->
        <div
          class="preview"
          v-html="parsedMarkdown"
          style="overflow: auto; height: 100%"
        ></div>
      </div>
    </div>

    <!-- 学习清单模态框 -->
    <Teleport to="body">
      <div v-if="showListModal" class="modal-overlay" @click.self="closeModal">
        <div class="modal-content" @click.stop>
          <div class="modal-header">
            <h2>任务清单</h2>
            <button class="close-button" @click.stop="closeModal">
              <el-icon><Delete /></el-icon>
            </button>
          </div>
          <div class="task-list">
            <div v-for="task in tasks" :key="task.id" class="task-item">
              <label class="checkbox-container">
                <input
                  type="checkbox"
                  :checked="task.completed"
                  @change.stop="toggleTask(task.id)"
                />
                <span class="checkmark"></span>
                <span :class="{ 'task-completed': task.completed }">{{
                  task.content
                }}</span>
              </label>
            </div>
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<style scoped>
@import "/src/css/base.css";
@import "/src/css/study-plan/index.css";

.button-group {
  display: flex;
  align-items: center;
  gap: 15px;
}

.study-list-button {
  padding: 12px 24px;
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
  display: flex;
  align-items: center;
  gap: 8px;
  height: 40px;
}

.study-list-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(59, 130, 246, 0.3);
  background: linear-gradient(135deg, #2563eb, #1d4ed8);
}

.study-list-button .el-icon {
  font-size: 1.2em;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.modal-content {
  position: relative;
  background: white;
  border-radius: 16px;
  padding: 24px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  z-index: 10000;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h2 {
  margin: 0;
  font-size: 1.25rem;
  color: #1f2937;
}

.close-button {
  background: none;
  border: none;
  color: #6b7280;
  cursor: pointer;
  padding: 4px;
  transition: color 0.2s;
}

.close-button:hover {
  color: #ef4444;
}

.task-list {
  max-height: 400px;
  overflow-y: auto;
}

.task-item {
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
}

.task-item:last-child {
  border-bottom: none;
}

.checkbox-container {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 1rem;
  color: #4b5563;
  gap: 12px;
}

.checkbox-container input {
  display: none;
}

.checkmark {
  width: 20px;
  height: 20px;
  border: 2px solid #3b82f6;
  border-radius: 6px;
  position: relative;
  transition: all 0.2s;
}

.checkbox-container input:checked + .checkmark {
  background: #3b82f6;
}

.checkbox-container input:checked + .checkmark:after {
  content: "";
  position: absolute;
  left: 6px;
  top: 2px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.task-completed {
  text-decoration: line-through;
  color: #9ca3af;
}

.task-list::-webkit-scrollbar {
  width: 6px;
}

.task-list::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.task-list::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.task-list::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>
